<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>聊天室</title>
<link rel="shortcut icon" href="favicon.png">
<link rel="icon" href="favicon.png" type="image/x-icon">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<style>
	
</style>
</head>

<body>
<div class="chatbox">
  <div class="chat_top fn-clear">
    <div class="logo"><img src="images/logo.png" width="190" height="60"  alt=""/></div>
    <div class="uinfo fn-clear">
      <div class="uface"><img src="images/hetu.jpg" width="40" height="40"  alt=""/></div>
      <div class="uname">
        <span>游客</span><i class="fontico down"></i>
        <ul class="managerbox">
          <!--<li><a href="#"><i class="fontico lock"></i>修改密码</a></li>-->
          <li><a href="javascript:alert('暂未开发');"><i class="fontico logout"></i>退出登录</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="chat_message fn-clear">
    <div class="chat_left">
      <div class="message_box" id="message_box" tofd="-1">
        <!--<div class="msg_item fn-clear">-->
          <!--<div class="uface"><img src="images/53f442834079a.jpg" width="40" height="40"  alt=""/></div>-->
          <!--<div class="item_right">-->
            <!--<div class="msg">(Visual) FoxPro, 4th Dimension/4D, Alice, APL, Arc, Automator, Awk, Bash, bc, Bourne shell, C++CLI, CFML, cg, CL (OS/400), Clean, Clojure, Emacs Lisp, Factor, Forth, Hack, Icon, Inform, Io, Ioke, J, JScript.NET, LabVIEW, LiveCode, M4, Magic, Max/MSP, Modula-2, Moto, NATURAL, OCaml, OpenCL, Oz, PILOT, Programming Without Coding Technology, Prolog, Pure Data, Q, RPG (OS/400), S, Smalltalk, SPARK, Standard ML, TOM, VBScript, Z shell</div>-->
            <!--<div class="name_time">白猫 · 1分钟前</div>-->
          <!--</div>-->
        <!--</div>-->
        <!---->
        <!--<div class="msg_item fn-clear">-->
          <!--<div class="uface"><img src="images/hetu.jpg" width="40" height="40"  alt=""/></div>-->
          <!--<div class="item_right">-->
            <!--<div class="msg own">那个统计表也不能说明一切</div>-->
            <!--<div class="name_time">河图 · 30秒前</div>-->
          <!--</div>-->
        <!--</div>-->

      </div>
      <div class="write_box">
        <textarea id="message" name="message" class="write_area" placeholder="说点啥吧... （ps: 快捷键Ctrl+Enter键可以发送消息）"></textarea>
        <input type="hidden" name="fromname" id="fromname" value="" />
        <input type="hidden" name="to_uid" id="to_uid" value="0">
        <div class="facebox fn-clear">
          <div class="expression"></div>
          <div class="chat_type" id="chat_type" style="float:left;margin-left:10%;">群聊</div>
		  <input type="file" id="file" style="float:right;margin-right:20px">
		</div>
		<div class="facebox fn-clear">
		  <button name="" class="sub_but" style="float:right;margin-right:10%">创建房间</button>
		  <button name="" class="sub_but" style="float:left;margin-left:10%;">加入房间</button>
		</div>
		<div class="facebox fn-clear">
		<div style="margin:0px 10px;height:100%;clear:both;display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:space-around">
		  <button name="" class="sub_but sendMsg" style="margin-left:10%;margin-right:10px">发送消息</button>
		  <button name="" class="sub_but sendAudio" style="margin-left:10px;margin-right:10px">发送语音</button>
		  <button name="" class="sub_but sendVideo" style="margin-left:10px;margin-right:10px">视屏通话</button>
		  <button name="" class="sub_but sendFile" style="margin-left:10px;margin-right:10%">发送文件</button>
		</div>
		</div>
      </div>
    </div>
    <div class="chat_right">
      <ul class="user_list" title="双击用户私聊">
        <li class="fn-clear selected"><em>所有用户</em></li>
        <li class="fn-clear" data-fd="-1"><span><img src="images/hetu.jpg" width="30" height="30"  alt=""/></span><em>群聊</em><small class="online" title="在线"></small>
		<span class="notice" style=" float:right;display:none;width:30px; height:30px; background-color:#F00; border-radius:15px;line-height:0px">
			<span style="height:50px; line-height:30px; display:block; color:#FFF; text-align:center">0</span>
		</span>
		</li>
      </ul>
	  <div style="display:none;height:40%;width:auto" class="media">
		<video controls="controls" autoplay="autoplay" style="width:100%;height:100%"><video>
	  </div>
	  <img id="recv">
    </div>
	<canvas id="canvas" style="display:none"></canvas>
  </div>
</div>


<link href="toastr/toastr.min.css" rel="stylesheet">
<script src="toastr/toastr.min.js"></script>
<script src="js/FileSaver.js"></script>
<script type="text/javascript">
	//openFile('aaa');
	
	/*
	type==1,有新连接建立
	type=2,连接成功
	type=3,断开连接
	type=4,消息
	type=5,文件
	type=6,视频数据
	type=7,语音数据
	
	tofd==-1,群发
	tofd=fd,发送到指定连接fd
	
	userInfo:{
		avatar:(string),用户头像
		fd:(int),用户连接fd
		nickname:(string),用户昵称
	}
	*/

  //基本配置

  var messageOpts = {
      "positionClass" : "toast-top-center",//弹出窗的位置
  };
  toastr.options = messageOpts;

//获取用户信息
var nickname = getName();


var index = Math.floor((Math.random()*734));
if(!index) index = 1;

var userInfo = {
    //'token':getToken(),
    'nickname':nickname,
    'avatar':"images/75X75/gs ("+index+").gif",
}



//连接ws
var recv=document.getElementById('recv');
var ws = new WebSocket("ws://39.106.207.193:9501");
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext("2d");
var video = document.querySelector('video');
 var draw = function(){
            ctx.drawImage(video,0,0, canvas.width, canvas.height);
			console.log(video.src);
            if(video.src){
				var tofd=parseInt($(".message_box:visible").attr("tofd"));
				var		 obj={
							tofd:tofd,
							type:6,
							stream:canvas.toDataURL("image/jpeg", 0.5)
						 };
				console.log("send:",obj);
                ws.send(JSON.stringify(obj));
            }
            setTimeout(draw, 100);
        }

ws.onopen = function (evt) {

    console.log('连接成功');
	var data={};
    //绑定用户信息
    nickname = prompt("请输入您的昵称",nickname);
    if(nickname){
        userInfo['nickname'] =nickname;
    }
    
    $('.uinfo .uface img').attr('src',userInfo.avatar);
    $('.uinfo .uname span').html(userInfo.nickname);
	data.userInfo=userInfo;
	data.type=2;
	data.tofd=-1;
    //var data = { 'a':'login','userInfo':userInfo };
    //ws.send(JSON.stringify(data));
	console.log(data);
	ws.send(JSON.stringify(data));
}

ws.onclose = function (evt) {
    toastr.success('连接关闭');
}

ws.onerror = function (evt,e) {
    console.log(e);
}

window.onbeforeunload=function(){
	websocket.close();
}

ws.onmessage = function (evt) {

    var data = JSON.parse(evt.data);

    //console.log(data);

	//有新连接
    if(parseInt(data.type) == 1){
		let html="",left="";
		html='<li class="fn-clear" data-fd="'+data.fd+'"><span><img src="'+data.userInfo.avatar+'" width="30" height="30" alt=""></span><em>'+data.userInfo.nickname+'</em><small class="online" title="在线"></small><span class="notice" style=" float:right;display:none;width:30px; height:30px; background-color:#F00; border-radius:15px;line-height:0px"><span style="height:50px; line-height:30px; display:block; color:#FFF; text-align:center">0</span></span></li>';
		left="<div style='display:none;' class='message_box' tofd='"+data.fd+"'></div>";
		$(".user_list").append(html);
		$(".write_box").before(left);
    }
	
	//连接建立
    if(parseInt(data.type) == 2){
		$(".chatbox").attr("fd",data.fd);
		if(data.list){
			let html="",left="";
			for (let key in data.list){
				let col="#"+Math.floor(Math.random()*0xffffff).toString(16);
				html +='<li class="fn-clear" data-fd="'+key+'"><span><img src="'+data.list[key].avatar+'" width="30" height="30" alt=""></span><em>'+data.list[key].nickname+'</em><small class="online" title="在线"></small><span class="notice" style=" float:right;display:none;width:30px; height:30px; background-color:#F00; border-radius:15px;line-height:0px"><span style="height:50px; line-height:30px; display:block; color:#FFF; text-align:center">0</span></span></li>';
				left+="<div style='display:none;' class='message_box' tofd='"+key+"'></div>";
			}
			$(".user_list").append(html);
			$(".write_box").before(left);
		}
    }

    //断开连接
    if(data.type == 3){
		let name=$(".user_list li[data-fd='"+data.fd+"'] em").text();
        toastr.success(name+"退出聊天");
        $(".user_list li[data-fd='"+data.fd+"']").remove();

    }

    //文本信息
    if(data.type == 4){
		//data.userInfo=getUserInfo(data.fd);
        addMessage(data);
    }
	
	//文件信息
	if(data.type==5){
		addMessage(data);
	}
	
	if(data.type==6){
		console.log("server:"+data);
		//$(".media").show();
		recv.src=data.stream;
	}

}


function getUserInfo(fd){
	let userInfo={};
	userInfo.nickname=$("li[data-fd='"+parseInt(fd)+"'] em").text();
	userInfo.avatar=$("li[data-fd='"+parseInt(fd)+"'] span img").attr("src");
	return userInfo;
}



//页面操作
$(document).ready(function(e) {

	$('#message_box').scrollTop($("#message_box")[0].scrollHeight + 20);
	$('.uname').hover(
	    function(){
		    $('.managerbox').stop(true, true).slideDown(100);
	    },
		function(){
		    $('.managerbox').stop(true, true).slideUp(100);
		}
	);
	
	var tofd   = -1; // 默认为-1,表示发送给所有用户
	//var to_uname = '';


	$('.user_list').on('click','li',function(){
		to_uname = $(this).find('em').text();
		tofd   = $(this).attr('data-fd');
		if(tofd==-1){
		    $("#toname").val('');
			$('#chat_type').text('群聊');
		}else{
		    $("#toname").val(tofd);
			$('#chat_type').text('您正和 ' + to_uname + ' 聊天');
		}
		
		$(".message_box").each(function(index){
			if(parseInt($(this).attr('tofd'))==tofd){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
		$(this).children(".notice").find('span').html("0");
		$(this).children(".notice").hide();
		$(this).addClass('selected').siblings().removeClass('selected');
	    $('#message').focus().attr("placeholder", "您对"+to_uname+"说：");
        return false;
	});
	
	$('.sendMsg').click(function(event){
	    sendMessage();
	    return false;
	});
	
	$('.sendFile').click(function(e){
		let file=$('#file').get(0).files[0];
		if(!file){
			alert("您还未选择任何文件！");
		}else{
			sendFile(file);	
		}
	});
	
	$(".sendVideo").click(function(e){
		let success=function(stream) {
						 
						 $(".media").show();
						 //video.srcObject = stream;
						 video.src=window.URL.createObjectURL(stream);
						 video.onloadedmetadata = function(e) {
						   video.play();
						   draw();
						 }
						 
						 
					}
		sendMedia({video: true,audio:true},success);
	});
	
	$(".sendAudio").click(function(e){
	
	});
	
	/*按下按钮或键盘按键*/
	$("#message").keydown(function(event){
		var e = window.event || event;
        var k = e.keyCode || e.which || e.charCode;
		//按下ctrl+enter发送消息

		if((event.ctrlKey && (k == 13 || k == 10) )){
			sendMessage();
		}
	});
	
	/*
	$(document).on("click","img",function(e){
		let width=window.screen.width*0.8;
		let height=width/$(this).width()*$(this).height();
		$(this).css({
			position:'absolute',
			width:width,
			height:height,
			top:(window.screen.height-height)/2,
			left:(window.screen.width-width)/2,
			zIndex:1
		});
	});
	*/

});

/**
 * 获取token
 * @returns {string}
 */
 function sendMedia(obj,callback){
	navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;

		if (navigator.getUserMedia) {
		   navigator.getUserMedia(obj,callback
			  ,function(err) {
				 alert(err.name + ": " + err.message);
			  }
			   );
		} else {
			if(navigator.mediaDevices.getUserMedia){
				navigator.mediaDevices.getUserMedia(obj).then(callback)
					.catch(function(err) {
					  alert(err.name + ": " + err.message);
					});
			}else{
				alert("getUserMedia not supported");
			}
		}
		
 }
 
 function sendFile(file){
	let fileReader=new FileReader();
	let data={
		file:{
			name:getFileName(file.name),
			type:file.type,
			size:file.size
		},
		type:5,
		tofd:parseInt($(".message_box:visible").attr("tofd"))
	}
	fileReader.addEventListener("load",function(e){//文件加载完成
		//data.file.data=fileReader.result;
		data.file.sendSize=0;
		var start=0;
		toastr.info('正在发送 '+data.file.name+' 请耐心等候...');
		var id=setInterval(function(){
			if(data.file.sendSize<=data.file.size){
				data.file.sendSize+=1*1024*1024;//每回发送1M数据
				data.file.data=fileReader.result.slice(start,start+1*1024*1024);
				ws.send(JSON.stringify(data));
				start+=1*1024*1024;
				console.log("send:"+data.file.sendSize+"字节");
				toastr.info('已发送 '+data.file.sendSize+'字节');
			}else{
				data.file.sendSize=data.file.size;
				clearInterval(id);
				toastr.clear();//清除当前的列表
				toastr.success("文件 ["+data.file.name+"] 发送完成!");
			}
		},1000); 
		//json=JSON.stringify(data);
		//ws.send(json);
		
	},false);//冒泡过程中执行
	
	fileReader.addEventListener("error",function(e){
		console.log(fileReader.error);
	});
	
	if(file){
		fileReader.readAsDataURL(file);
	}else{
		alert("您还未选择任何文件！");
	}
	
	
 }
 
 function writeFile(file){
	var file = new File([file.data], file.name, { type: "text/plain;charset=utf-8" });
	saveAs(file);
	return true;

	}

function getFileName(filename){
	let date=new Date();
	let d=date.getDate().toString();
	let mm=date.getMonth().toString();
	let y=date.getFullYear().toString();
	let h=date.getHours().toString();
	let m=date.getMinutes().toString();
	let s=date.getSeconds().toString();
	if(h<10){
		h="0"+h;
	}
	if(m<10){
		m="0"+m;
	}
	if(s<10){
		s="0"+s;
	}
	return y+mm+d+h+m+s+"-"+filename;
}
 
function getToken() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid.replace(/-/g,'');
}

/**
 * 发送信息
 * @param obj:{
	
 }
 */
function sendMessage(){
	var obj={};
    var msg = $("#message").val();
	obj.msg=msg;
	obj.tofd=$(".message_box:visible").attr("tofd");
	obj.type=4;
	obj.tofd=parseInt(obj.tofd)
	if( obj.tofd!= -1){
	    msg = '（悄悄话）： ' + msg;
	}
	console.log("send:",obj);
    ws.send(JSON.stringify(obj));

//	var avatar = "images/hetu.jpg";
//    addMessage(msg,from_name,avatar);
	$("#message").val('');
}

/**
 * 添加信息到box
 */
function addMessage(obj) {
	var tt=(new Date(parseInt(obj.last_time+"000"))).toLocaleString();
	if(obj.file){//存在文件
		let type=obj.file.type.slice(0,obj.file.type.indexOf('/'));
		let name=obj.file.name.slice(obj.file.name.indexOf('-')+1);
		switch (type){
			case 'image':
				obj.msg="<img src='"+obj.file.url+"' style='width:100px'>";
				break;
				
			default:
				obj.msg="<a href='"+obj.file.url+"' download='"+name+"'>"+name+"&emsp; 【下载】"+"</a>";
				
		}
	}
	
    var htmlData =   '<div class="msg_item fn-clear">'
        + '   <div class="uface"><img src="'+obj.userInfo.avatar+'" width="40" height="40"  alt=""/></div>'
        + '   <div class="item_right">'
        + '     <div class="msg own">' + obj.msg + '</div>'
        + '     <div class="name_time">' + tt + ' · '+obj+'</div>'
        + '   </div>'
        + '</div>';
	if(obj.tofd==-1){
		obj.fd=-1;
	}
	let fd=$(".chatbox").attr("fd");
	if(fd==obj.fd){//发给自己
		obj.fd=obj.tofd;
	}else{
		let num=parseInt($("li[data-fd='"+obj.fd+"'] .notice span").text());
		num+=1;
		$("li[data-fd='"+obj.fd+"'] .notice span").html(num.toString());
		$("li[data-fd='"+obj.fd+"'] .notice").show();
	}
	
    $(".message_box[tofd='"+obj.fd+"']").append(htmlData);
    $('.message_box:visible').scrollTop($(".message_box:visible")[0].scrollHeight + 20);
}

/**
 * 随机姓名
 */
function getName(){
    var familyNames = new Array(
        "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
        "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
        "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏",
        "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
        "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦",
        "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳",
        "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺",
        "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
        "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余",
        "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹"
    );
    var givenNames = new Array(
        "子璇", "淼", "国栋", "夫子", "瑞堂", "甜", "敏", "尚", "国贤", "贺祥", "晨涛",
        "昊轩", "易轩", "益辰", "益帆", "益冉", "瑾春", "瑾昆", "春齐", "杨", "文昊",
        "东东", "雄霖", "浩晨", "熙涵", "溶溶", "冰枫", "欣欣", "宜豪", "欣慧", "建政",
        "美欣", "淑慧", "文轩", "文杰", "欣源", "忠林", "榕润", "欣汝", "慧嘉", "新建",
        "建林", "亦菲", "林", "冰洁", "佳欣", "涵涵", "禹辰", "淳美", "泽惠", "伟洋",
        "涵越", "润丽", "翔", "淑华", "晶莹", "凌晶", "苒溪", "雨涵", "嘉怡", "佳毅",
        "子辰", "佳琪", "紫轩", "瑞辰", "昕蕊", "萌", "明远", "欣宜", "泽远", "欣怡",
        "佳怡", "佳惠", "晨茜", "晨璐", "运昊", "汝鑫", "淑君", "晶滢", "润莎", "榕汕",
        "佳钰", "佳玉", "晓庆", "一鸣", "语晨", "添池", "添昊", "雨泽", "雅晗", "雅涵",
        "清妍", "诗悦", "嘉乐", "晨涵", "天赫", "玥傲", "佳昊", "天昊", "萌萌", "若萌"
    );


    var i = Math.floor((Math.random()*familyNames.length));
    var familyName = familyNames[i];
    var j = Math.floor((Math.random()*givenNames.length));
    var givenName = givenNames[i];
    var name = familyName + givenName;


    return name;
}



</script>
</body>
</html>
